<template>
  <nav-bar>
    <template v-slot:default>{{title}}</template>
  </nav-bar>

  <div class="address-edit">
  <van-address-edit
      :area-list="areaList"
      :address-info="addressInfo"
      :show-delete="type==='edit'"
      show-set-default
      show-search-result
      :search-result="searchResult"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
  />
  </div>

</template>

<script>
import {ref, reactive, toRefs, onMounted, computed} from "vue";
import {useRoute, useRouter} from "vue-router";
import {Toast} from "vant";
import {tdist} from "utils/address";
import {getAddressDetail, addAddress, editAddress, deleteAddress, defaultAddress} from "network/address";
import NavBar from "components/common/navbar/NavBar";
export default {
  name: "AddressEdit",
  components: {
    NavBar
  },
  setup() {
    const route = useRoute(),
        router = useRouter()

    // 数据模型
    const state = reactive({
      // title: '',
      type: 'add',
      addressId: '',
      areaList: {
        province_list: {},
        city_list: {},
        county_list: {},
      },
      addressInfo: {},
      searchResult: [],
    })

    const title = computed(() => state.type === 'add' ? '添加地址' : '编辑地址')

    // 数据方法
    const onSave = el => {
      const data = {
        name: el.name,
        address: el.addressDetail,
        phone: el.tel,
        province: el.province,
        city: el.city,
        county: el.county,
        is_default: el.isDefault ? 1 : 0
      }
      if (state.type === 'add') {
        addAddress(data).then(res => Toast.success('添加地址成功') && setTimeout(() => router.back(), 1000))
      } else if (state.type === 'edit') {
        editAddress(state.addressId, data).then(res => Toast.success('编辑地址成功') && setTimeout(() => router.back(), 1000))
      }
    }
    const onDelete = () => {
      deleteAddress(state.addressId).then(res => Toast.success('删除成功!') && setTimeout(() => router.back(), 1000))
    }

    onMounted(() => {
      const {type, addressId} = route.query
      state.type = type
      state.addressId = addressId
      // state.title = type === 'add' ? '添加地址' : '编辑地址'
      // 省市区 列表数据
      let _province_list = {},
          _city_list = {},
          _county_list = {}
      tdist.getLev1().forEach(p => {
        _province_list[p.id] = p.text
        tdist.getLev2(p.id).forEach(c => {
          _city_list[c.id] = c.text
          tdist.getLev3(c.id).forEach(q => {
            _county_list[q.id] = q.text
          })
        })
      })
      state.areaList.province_list = _province_list
      state.areaList.city_list = _city_list
      state.areaList.county_list = _county_list
      // 如果编辑地址
      if (type === 'edit') {
        getAddressDetail(addressId).then(res => {
          const addressDetail = res
          let _areaCode = ''
          const province = tdist.getLev1()
          Object.entries(state.areaList.county_list).forEach(([id, text]) => {
            // 先找出当前对应的区
            if (text == addressDetail.county) {
              // 找到区对应的几个省份
              const provinceIndex = province.findIndex(item => item.id.substr(0, 2) == id.substr(0, 2))
              // 找到区对应的几个市区
              // eslint-disable-next-line no-unused-vars
              const cityItem = Object.entries(state.areaList.city_list).filter(([cityId, city]) => cityId.substr(0, 4) == id.substr(0, 4))[0]
              // 对比找到的省份和接口返回的省份是否相等，因为有一些区会重名
              if (province[provinceIndex].text == addressDetail.province && cityItem[1] == addressDetail.city) {
                _areaCode = id
              }
            }
          })
          // 初始化地址信息
          state.addressInfo = {
            name: addressDetail.name,
            tel: addressDetail.phone,
            province: addressDetail.province,
            city: addressDetail.city,
            county: addressDetail.county,
            areaCode: _areaCode,
            addressDetail: addressDetail.address,
            isDefault: !!addressDetail.is_default,
          }
        })
      }
    })
    return {
      ...toRefs(state), onSave, onDelete, title
    }
  }
}
</script>

<style lang="scss">
.address-edit {
  margin-top: 45px;
  .van-button:first-of-type {
    background: var(--color-tint);
    border-color: var(--color-tint)
  }
}
</style>